package com.gs.synedocket.util;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.graphics.ImageFormat;
import android.graphics.Matrix;
import android.graphics.RectF;
import android.graphics.SurfaceTexture;
import android.hardware.camera2.CameraAccessException;
import android.hardware.camera2.CameraCaptureSession;
import android.hardware.camera2.CameraCharacteristics;
import android.hardware.camera2.CameraDevice;
import android.hardware.camera2.CameraManager;
import android.hardware.camera2.CameraMetadata;
import android.hardware.camera2.CaptureRequest;
import android.hardware.camera2.CaptureResult;
import android.hardware.camera2.TotalCaptureResult;
import android.hardware.camera2.params.MeteringRectangle;
import android.hardware.camera2.params.StreamConfigurationMap;
import android.media.Image;
import android.media.ImageReader;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.util.Size;
import android.util.SparseIntArray;
import android.view.Surface;
import android.view.TextureView;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.core.app.ActivityCompat;

import com.gs.synedocket.constant.AllConstants;
import com.gs.synedocket.constant.HandleCode;
import com.gs.synedocket.control.AutoTexturePreviewView;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
public class CameraUtil {

    private static final String TAG_PREVIEW = "预览";
    private static final String FILENAME = "face_photo.jpg";
    private final Activity activity;
    private final AutoTexturePreviewView previewView;
    private Size mPreviewSize;
    private final TextureView textureView;
    private String mCameraId;
    private CameraDevice mCameraDevice;
    private ImageReader mImageReader;
    private Surface mPreviewSurface;
    private CaptureRequest.Builder mPreviewRequestBuilder;
    private CameraCaptureSession mCaptureSession;
    private final CameraManager manager;
    // 防止在关闭相机之前应用程序退出
    private final Semaphore mCameraOpenCloseLock = new Semaphore(1);
    private static final SparseIntArray ORIENTATION = new SparseIntArray();
    private final Handler handler;

    static {
        ORIENTATION.append(Surface.ROTATION_0, 90);
        ORIENTATION.append(Surface.ROTATION_90, 0);
        ORIENTATION.append(Surface.ROTATION_180, 270);
        ORIENTATION.append(Surface.ROTATION_270, 180);
    }


    public CameraUtil(Activity activity, AutoTexturePreviewView previewView, TextureView textureView, Handler handler) {
        this.previewView = previewView;
        this.textureView = textureView;
        this.activity = activity;
        this.handler = handler;
        manager = (CameraManager) activity.getSystemService(Context.CAMERA_SERVICE);
    }

    public void open() {
        handler.postDelayed(() -> {
            if (textureView == null) {
                return;
            }
            if (textureView.isAvailable()) {
                mCameraId = "0";
                openCamera(textureView.getWidth(), textureView.getHeight());
            } else {
                textureView.setSurfaceTextureListener(textureListener);
            }
        }, 300);
    }

    /**
     * 拍照
     */
    public void takePhoto() {
        capture(activity);
    }

    private void capture(Activity activity) {
        try {
            if (mCaptureSession == null) {
                handler.sendEmptyMessage(HandleCode.MSG_CAPTURE_ERROR);
                return;
            }
            // 创建请求拍照的CaptureRequest
            CaptureRequest.Builder mCaptureBuilder = mCameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_STILL_CAPTURE);
            mCaptureBuilder.addTarget(mPreviewSurface);
            mCaptureBuilder.addTarget(mImageReader.getSurface());

            // 聚焦
            mCaptureBuilder.set(CaptureRequest.CONTROL_AE_MODE,
                    CaptureRequest.CONTROL_AF_MODE_CONTINUOUS_PICTURE);
            // 获取屏幕方向
            int rotation = activity.getWindowManager().getDefaultDisplay().getRotation();
            // 设置拍照方向
            mCaptureBuilder.set(CaptureRequest.JPEG_ORIENTATION, ORIENTATION.get(rotation));
            // 停止预览
            mCaptureSession.stopRepeating();
            mCaptureSession.capture(mCaptureBuilder.build(), mPreviewCaptureCallback, null);
        } catch (Exception e) {
            handler.sendEmptyMessage(HandleCode.MSG_CAPTURE_ERROR);
            e.printStackTrace();
        }
    }

    // 获取预览帧数据
    private final CameraCaptureSession.CaptureCallback mPreviewCaptureCallback = new CameraCaptureSession.CaptureCallback() {

        @Override
        public void onCaptureCompleted(@NonNull CameraCaptureSession session, @NonNull CaptureRequest request, @NonNull TotalCaptureResult result) {
            super.onCaptureCompleted(session, request, result);
        }

        @Override
        public void onCaptureProgressed(@NonNull CameraCaptureSession session, @NonNull CaptureRequest request, @NonNull CaptureResult partialResult) {
            super.onCaptureProgressed(session, request, partialResult);
        }

    };

    private void openCamera(int width, int height) {
        setupCamera(width, height);
        configureTransform(width, height);
        try {
            if (!mCameraOpenCloseLock.tryAcquire(2500, TimeUnit.MILLISECONDS)) {
                throw new RuntimeException("Time out waiting to lock camera opening");
            }
            if (ActivityCompat.checkSelfPermission(activity, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
                handler.sendEmptyMessage(HandleCode.MSG_CAPTURE_ERROR);
                return;
            }
            // 打开相机，第一个参数指示打开哪个摄像头，第二个参数stateCallback为相机的状态回调接口
            // 第三个参数用来确定Callback在哪个线程执行，为null的话就在当前线程执行
            manager.openCamera(mCameraId, stateCallback, null);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // Surface状态回调
    private final TextureView.SurfaceTextureListener textureListener = new TextureView.SurfaceTextureListener() {
        @Override
        public void onSurfaceTextureAvailable(@NonNull SurfaceTexture surface, int width, int height) {
            openCamera(width, height);
        }

        @Override
        public void onSurfaceTextureSizeChanged(@NonNull SurfaceTexture surface, int width, int height) {

        }

        @Override
        public boolean onSurfaceTextureDestroyed(@NonNull SurfaceTexture surface) {
            return false;
        }

        @Override
        public void onSurfaceTextureUpdated(@NonNull SurfaceTexture surface) {

        }
    };

    private void configureTransform(int viewWidth, int viewHeight) {
        if (previewView == null || mPreviewSize == null) {
            return;
        }
        int rotation = activity.getWindowManager().getDefaultDisplay().getRotation();
        Matrix matrix = new Matrix();
        RectF viewRect = new RectF(0, 0, viewWidth, viewHeight);
        RectF bufferRect = new RectF(0, 0, mPreviewSize.getHeight(), mPreviewSize.getWidth());
        float centerX = viewRect.centerX();
        float centerY = viewRect.centerY();
        if (Surface.ROTATION_90 == rotation || Surface.ROTATION_270 == rotation) {
            bufferRect.offset(centerX - bufferRect.centerX(), centerY - bufferRect.centerY());
            matrix.setRectToRect(viewRect, bufferRect, Matrix.ScaleToFit.FILL);
            float scale = Math.max(
                    (float) viewHeight / mPreviewSize.getHeight(),
                    (float) viewWidth / mPreviewSize.getWidth());
            matrix.postScale(scale, scale, centerX, centerY);
            matrix.postRotate(90 * (rotation - 2), centerX, centerY);
        } else if (Surface.ROTATION_180 == rotation) {
            matrix.postRotate(180, centerX, centerY);
        }
        textureView.setTransform(matrix);
    }

    private void setupCamera(int width, int height) {
        // 获取摄像头的管理者CameraManager
        CameraManager manager = (CameraManager) activity.getSystemService(Context.CAMERA_SERVICE);
        try {
            for (String cameraId : manager.getCameraIdList()) {
                CameraCharacteristics characteristics = manager.getCameraCharacteristics(cameraId);
                Integer lens = characteristics.get(CameraCharacteristics.LENS_FACING);
                if (lens == null) continue;
                // 打开后置
                if (lens == CameraCharacteristics.LENS_FACING_FRONT) {
                    // 获取StreamConfigurationMap，管理摄像头支持的所有输出格式和尺寸
                    StreamConfigurationMap map = characteristics.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP);
                    if (map == null) continue;
                    mPreviewSize = getOptimalSize(map.getOutputSizes(SurfaceTexture.class), width, height);
                    int orientation = activity.getResources().getConfiguration().orientation;
                    if (orientation == Configuration.ORIENTATION_LANDSCAPE) {
                        previewView.setPreviewSize(mPreviewSize.getWidth(), mPreviewSize.getHeight());
                    } else {
                        previewView.setPreviewSize(mPreviewSize.getHeight(), mPreviewSize.getWidth());
                    }
                    mCameraId = cameraId;
                    break;
                }
            }
        } catch (CameraAccessException e) {
            Log.i(AllConstants.TAG, Objects.requireNonNull(e.getMessage()));
            e.printStackTrace();
        }
    }

    private Size getOptimalSize(Size[] sizeMap, int width, int height) {
        List<Size> sizeList = new ArrayList<>();
        for (Size option : sizeMap) {
            if (width > height) {
                if (option.getWidth() > width && option.getHeight() > height) {
                    sizeList.add(option);
                }
            } else {
                if (option.getWidth() > height && option.getHeight() > width) {
                    sizeList.add(option);
                }
            }
        }
        if (sizeList.size() > 0) {
            return Collections.min(sizeList, (lhs, rhs) -> Long.signum(lhs.getWidth() * lhs.getHeight() - rhs.getWidth() * rhs.getHeight()));
        }
        return sizeMap[0];
    }

    // 當相機打开后会回调onOpened
    private final CameraDevice.StateCallback stateCallback = new CameraDevice.StateCallback() {
        @Override
        public void onOpened(@NonNull CameraDevice camera) {
            mCameraOpenCloseLock.release();
            mCameraDevice = camera;
            // 开启预览
            startPreview();
        }

        @Override
        public void onDisconnected(@NonNull CameraDevice camera) {
            mCameraOpenCloseLock.release();
            camera.close();
            Log.i("demo", "CameraDevice Disconnected");
        }

        @Override
        public void onError(@NonNull CameraDevice camera, int error) {
            mCameraOpenCloseLock.release();
            camera.close();
            Log.i("demo", "CameraDevice Error");
        }
    };

    private void startPreview() {
        setupImageReader();
        SurfaceTexture mSurfaceTexture = textureView.getSurfaceTexture();
        if (mSurfaceTexture != null) {
            // 设置TextureView的缓冲区大小
            mSurfaceTexture.setDefaultBufferSize(mPreviewSize.getWidth(), mPreviewSize.getHeight());
            // 获取surface显示预览数据
            mPreviewSurface = new Surface(mSurfaceTexture);
            try {
                getPreviewRequestBuilder();
                // 创建相机捕获回话
                mCameraDevice.createCaptureSession(Arrays.asList(mPreviewSurface, mImageReader.getSurface()), new CameraCaptureSession.StateCallback() {

                    // CameraCaptureSession创建好后会回调这个方法
                    @Override
                    public void onConfigured(@NonNull CameraCaptureSession session) {
                        mCaptureSession = session;
                        repeatPreview();
                    }

                    @Override
                    public void onConfigureFailed(@NonNull CameraCaptureSession session) {

                    }

                    @Override
                    public void onClosed(@NonNull CameraCaptureSession session) {
                        super.onClosed(session);
                    }
                }, null); // 第三个参数确定callback在哪个线程执行，为null表示在当前线程执行
            } catch (CameraAccessException e) {
                e.printStackTrace();
            }
        }
    }

    private void setupImageReader() {
        // 前三个参数分别是需要的尺寸和格式，最后一个参数代表每次最多获取几帧数据
        mImageReader = ImageReader.newInstance(mPreviewSize.getWidth(), mPreviewSize.getHeight(), ImageFormat.JPEG, 1);
        // 监听ImageReader的事件，当有图像流数据可用时会回调onImageAvailable方法
        // 参数就是预览帧数据，可以对这帧数据进行处理
        mImageReader.setOnImageAvailableListener(reader -> {
            Image image = null;
            try {
                image = reader.acquireLatestImage();
            } catch (Exception e) {
                e.printStackTrace();
            }
            File saveFile = FileUtils.getInstance().createFile(activity, FILENAME);
            new Thread(new ImageSaver(image, saveFile, handler)).start();
        }, null);
    }

    /**
     * 创建预览请求的Builder（TEMPLATE_PREVIEW表示预览请求）
     */
    private void getPreviewRequestBuilder() {
        try {
            mPreviewRequestBuilder = mCameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW);
            // 设置预览的显示界面
            mPreviewRequestBuilder.addTarget(mPreviewSurface);
//        mPreviewRequestBuilder.addTarget(mImageReader.getSurface());
            mPreviewRequestBuilder.set(CaptureRequest.STATISTICS_FACE_DETECT_MODE,
                    CameraMetadata.STATISTICS_FACE_DETECT_MODE_FULL);
            MeteringRectangle[] meteringRectangles = mPreviewRequestBuilder.get(CaptureRequest.CONTROL_AE_REGIONS);
            if (meteringRectangles != null && meteringRectangles.length > 0) {
                Log.i("demo", "PreviewRequestBuilder： AF_REGIONS=" + meteringRectangles[0].getRect().toString());
            }
            mPreviewRequestBuilder.set(CaptureRequest.CONTROL_MODE, CaptureRequest.CONTROL_MODE_AUTO);
            mPreviewRequestBuilder.set(CaptureRequest.CONTROL_AF_TRIGGER, CaptureRequest.CONTROL_AF_TRIGGER_IDLE);
        } catch (Exception e) {
            handler.sendEmptyMessage(HandleCode.MSG_CAPTURE_ERROR);
            e.printStackTrace();
        }
    }

    private void repeatPreview() {
        mPreviewRequestBuilder.setTag(TAG_PREVIEW);
        CaptureRequest mPreviewRequest = mPreviewRequestBuilder.build();
        // 设置反复捕获数据的请求，这样预览界面就会一直有数据显示
        try {
            mCaptureSession.setRepeatingRequest(mPreviewRequest, mPreviewCaptureCallback, null);
        } catch (CameraAccessException e) {
            e.printStackTrace();
        }
    }

    public void closeCamera() {
        try {
            mCameraOpenCloseLock.acquire();
            if (mCaptureSession != null) {
                mCaptureSession.close();
                mCaptureSession = null;
            }
            if (mCameraDevice != null) {
                mCameraDevice.close();
                mCameraDevice = null;
            }
            if (mImageReader != null) {
                mImageReader.close();
                mImageReader = null;
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            mCameraOpenCloseLock.release();
        }
    }

    public static class ImageSaver implements Runnable {

        private final Image mImage;
        private File file;
        private Handler handler;

        public ImageSaver(Image image, File file, Handler handler) {
            this.mImage = image;
            this.file = file;
            this.handler = handler;
        }

        @Override
        public void run() {
            if (mImage != null) {
                FileOutputStream fos = null;
                try {
                    ByteBuffer buffer = mImage.getPlanes()[0].getBuffer();
                    byte[] data = new byte[buffer.remaining()];
                    buffer.get(data);
                    fos = new FileOutputStream(file);
                    fos.write(data, 0, data.length);
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    try {
                        mImage.close();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    if (fos != null) {
                        try {
                            fos.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    String base64 = ImageUtil.image2Base64(file.getAbsolutePath());
                    file.delete();
                    Message message = Message.obtain();
                    message.what = HandleCode.MSG_PHOTO;
                    message.obj = base64;
                    handler.sendMessage(message);
                }
            }
        }
    }
}
